package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractTiktokByTimeApiHandler;
import com.ittx.dzt.tiktok.util.CyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退货单增量下载
 * <p>
 * cy.returnOrder.download.byTimeFrame
 * /return_refund/202309/returns/search （售后单查询） https://partner.tiktokshop.com/docv2/page/650ab69edefece02be70785b?external_id=650ab69edefece02be70785b#Back%20To%20Top
 * </p>
 *
 * @author gywang
 * @since 2024-07-23
 */
@Slf4j
@Service
public class TiktokReturnOrderDownloadByTimeService extends AbstractTiktokByTimeApiHandler<TimeFrameDTO> {

	private static final Integer DEFAULT_PAGE_SIZE = 50;

	private static final List<String> RETURN_STATUS = Arrays.asList(
			"RETURN_OR_REFUND_REQUEST_PENDING",
			"REFUND_OR_RETURN_REQUEST_REJECT",
			"AWAITING_BUYER_SHIP",
			"BUYER_SHIPPED_ITEM",
			"REJECT_RECEIVE_PACKAGE",
			"RETURN_OR_REFUND_REQUEST_SUCCESS",
			"RETURN_OR_REFUND_REQUEST_CANCEL",
			"RETURN_OR_REFUND_REQUEST_COMPLETE"
	);

	@Autowired
	private TiktokReturnOrderDownloadByIdService tiktokReturnOrderDownloadByIdService;

	@Override
	protected String getMqTopic() {
		return TiktokApiConstant.Rocket.TIKTOK_DOWNLOAD_RETURN_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getTiktokMethod() {
		return TiktokApiConstant.DOWNLOAD_RETURN_LIST;
	}

	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.RETURNORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		Map<String, Boolean> logMap = new HashMap<>();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		// 探查成功时不返回完整数据,只返回数量
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	/**
	 * rds直接批量下载后下发，不经过拆分队列
	 *
	 * @param platformApiParamDTO
	 * @param timeFrameDTO
	 * @return
	 */
	@Override
	protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		String refundId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, String.valueOf(refundId));

	}


	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		params.put("shop_cipher", getShopCipher(platformApiParamDTO));
		params.put("page_size", DEFAULT_PAGE_SIZE);

		Map<String, Object> reqBody = new HashMap<>();

		reqBody.put("update_time_ge", timeFrameDTO.getFrom().toEpochSecond(ZoneOffset.of("+8")));
		reqBody.put("update_time_lt", timeFrameDTO.getTo().toEpochSecond(ZoneOffset.of("+8")));
		// 状态过滤
		List<String> statusList = CyUtil.getStatusList(platformApiParamDTO, "return");
		if (CollectionUtil.isNotEmpty(statusList)) {
			List<String> status = (List<String>) CollectionUtil.intersection(statusList, RETURN_STATUS);
			if (CollectionUtil.isNotEmpty(status))
				reqBody.put("return_status", status);
		}
		String pageToken = null;
		do {
			if (pageToken != null) {
				params.put("page_token", pageToken);
			}
			Result<?> result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, JacksonTool.toJson(reqBody), platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
			if (!result.isSuccess()) {
				return result;
			}
			Map<String, Object> resultMap = (Map<String, Object>) result.getData();
			Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
			// 售后单总数
			Integer total = Integer.parseInt(dataMap.get(RESULT_TOTAL).toString());
			pageToken = (String) dataMap.get("next_page_token");
			// 探查模式只返回总数
			if (open.constant.PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
				return Result.success().addData(total);
			}
			List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("return_orders");
			if (CollectionUtil.isNotEmpty(list)) {
				for (Map<String, Object> refund : list) {
					String refundId = (String) refund.get("return_id");
					sendToSplitTopic(platformApiParamDTO, refundId, logMap);
				}
			}

		} while (StringUtils.isNotBlank(pageToken));

		return Result.success(logMap);
	}

	/**
	 * sdk
	 * <p>
	 * 根据订单号下载售后单 ------- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String refundId) {
		Result<?> result = tiktokReturnOrderDownloadByIdService.getRefundById(platformApiParamDTO, refundId);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}
}
